import React, { Component } from 'react';
import { PageList } from 'mtui';

/**
 * @desc this.props.ajaxDo ajax对象
 */
export default class Pages extends Component {

    // 构造函数
    constructor(props) {
        super(props);
        this.state = {
            count: 0
        };
        this.refsPageList = null;
    }

    // 模拟 ajax 异步
    ajax = (current, refresh) => {
        // console.log('分页回调 ajax 请求 current:', current);
        // console.log(this.props.ajax);
        this.props.ajax(current).then( res => {
            if(res.success) {
                this.setState({
                    count: res.count
                }, () => {
                    if (refresh) {
                        this.refsPageList.refresh();
                    }
                });
            }
        });
    }

    // 分页点击后执行
    callback = (obj) => {
        this.ajax(obj.current);
    }

    // 默认选择第一页
    componentDidMount() {
        this.ajax(1);
    }

    render() {
        return (
            <div className="pagelist">
                <PageList ref={(c) => { this.refsPageList = c; }} current={1} pageSize={this.props.pageSize || 20} callback={this.callback} total={this.state.count} />
            </div>
        );
    }
}